package com.libre.controller;

import java.awt.print.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;

public class WinPrinter {

    public static void printPdf(List<File> files) {
        //构造一个文件选择器，默认为当前目录
        //File file = new File(fileName);//获取选择的文件
        //构建打印请求属性集
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        pras.add(new Copies(1)); //份数
//        //aset.add(MediaSize.ISO.A4); //纸张
//        // aset.add(Finishings.STAPLE);//装订
//        pras.add(Sides.DUPLEX);//单双面

        //设置打印格式，因为未确定文件类型，这里选择AUTOSENSE
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        //查找所有的可用打印服务
//        PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);
        PrintService[] printServices = PrinterJob.lookupPrintServices();

        PrintService useService = null;
        for (PrintService service : printServices) {
            System.out.println("service = " + service.getName());
//            if ("(PangLiuJie) HP DeskJet 2300 series".equals(service.getName())) {
            if ("Samsung M2070 Series".equals(service.getName())) {
                System.out.println("使用打印机 = " + service.getName());
                useService = service;
            }
        }
        //定位默认的打印服务
        //PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();

        DocPrintJob printJob = useService.createPrintJob();
        DocAttributeSet das = new HashDocAttributeSet();
        Doc doc = null;
        FileInputStream in = null;
        try {
            for (File file : files) {
                 in = new FileInputStream(file); // 构造待打印的文件流
                doc = new SimpleDoc(in, flavor, das);
            }
            printJob.addPrintJobListener(new MyPrintJobListener());
            printJob.print(doc, pras);
            System.out.println("getAttributes"+ printJob.getAttributes());
            System.out.println("PrintService"+ printJob.getPrintService());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (PrintException e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[])  {
        List<File> files = new ArrayList<>();
        files.add(new File("C:\\Users\\DELL\\Desktop\\类图.docx"));
//        files.add(new File("C:\\Users\\liujie\\Desktop\\打印文件\\b.pdf"));
        printPdf(files);

    }


}
